<?php

namespace interface\v1;
/*
*工作报告接口类
*/

class workReportAppClass extends index
{
    private const table = 'work_report';
    private const page = 'workReportDay';
    private const title = '工作汇报';

    /*查询条件*/
    public function search()
    {
        //状态
        $data['result']['typeOption'] = array("日报", "周报", "月报");
        $data['result']['timeOption'] = $this->timeOption;
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }


    public function home()
    {
        $data['result'] = [
            [
                'name' => '日报',
                'ico' => oaIndexAppClass::icon('dayReport'),
                'url' => '../dayReportEdit/dayReportEdit',
            ],
            [
                'name' => '周报',
                'ico' => oaIndexAppClass::icon('weekReport'),
                'url' => '../weekReportEdit/weekReportEdit',
            ],
            [
                'name' => '月报',
                'ico' => oaIndexAppClass::icon('monthReport'),
                'url' => '../monthReportEdit/monthReportEdit',
            ]
        ];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 日报日历
     */
    public function dayReportCalendar($date, $type = '日报'): array
    {
        $dayResult = [];
        $days = date('t', strtotime($date));
        $formatMonth = date('Y-m', strtotime($date));
        $now_week = date('w', strtotime(date('Y-m-01', strtotime($date))));
        for ($i = 0; $i < $now_week; $i++) {
            $dayResult[] = [
                'index' => ' ',
                'state' => ' ',
                'date' => ' ',
                'edit' => 0,
            ];
        }
        for ($i = 1; $i <= $days; $i++) {
            $today = $formatMonth . '-' . sprintf("%02d", $i);
            $temp = [
                'index' => $i,
                'date' => $today,
            ];
            //是否可点击
            if (strtotime($today) > time()) {
                $temp['edit'] = 0;
            } else {
                $temp['edit'] = 1;
            }
            if (self::total(array('table' => self::table, 'where' => "type = '$type' and location = '$today' and stid = '" . self::$stid . "'")) > 0) {
                $temp['state'] = '正常';
            } else {
                $temp['state'] = '缺报';
            }
            $dayResult[] = $temp;
        }
        return $dayResult;
    }

    /**
     * 周报日历
     * @param $date
     * @param string $type
     */
    public function weekReportCalendar($date, $type = '周报'): array
    {
        $dayResult = [];
        $days = date('t', strtotime($date));
        $formatMonth = date('Y-m', strtotime($date));
        $now_week = date('w', strtotime(date('Y-m-01', strtotime($date))));
        for ($i = 0; $i < $now_week; $i++) {
            $dayResult[] = [
                'index' => ' ',
                'state' => ' ',
                'date' => ' ',
                'edit' => 0,
            ];
        }
        for ($i = 1; $i <= $days; $i++) {
            $today = $formatMonth . '-' . sprintf("%02d", $i);
            $temp = [
                'index' => $i,
                'date' => $today,
            ];
            //是否可点击
            if (strtotime($today) > time() || date('w', strtotime($today)) != 1) {
                $temp['edit'] = 0;
            } else {
                $temp['edit'] = 1;
            }
            if (self::total(array('table' => self::table, 'where' => "type = '$type' and location = '$today' and stid = '" . self::$stid . "'")) > 0) {
                $temp['state'] = '正常';
            } else {
                $temp['state'] = '缺报';
            }
            $dayResult[] = $temp;
        }
        return $dayResult;
    }

    /**
     * 月报日历
     */
    public function monthReportCalendar($date): array
    {
        $dayResult = [];
        $year = date('Y', strtotime($date));
        for ($i = 1; $i <= 12; $i++) {
            $today = $year . '-' . sprintf("%02d", $i) . '-01';
            $temp = [
                'title' => $i . '月',
                'index' => $i,
                'month' => $year . '-' . sprintf("%02d", $i),
                'date' => $today,
            ];
            //是否可点击
            if (strtotime($today) > time()) {
                $temp['edit'] = 0;
            } else {
                $temp['edit'] = 1;
            }
            if (self::total(array('table' => self::table, 'where' => "type = '月报' and location = '$today' and stid = '" . self::$stid . "'")) > 0) {
                $temp['state'] = '正常';
            } else {
                $temp['state'] = '缺报';
            }
            $dayResult[] = $temp;
        }
        return $dayResult;
    }

    /**
     * 查找周一日期
     */
    public function findWeekOneDate($date): string
    {
        $weekDay = date('w', strtotime($date));
        if ($weekDay != 1) {
            //不是星期一
            $formatMonth = date('Y-m', strtotime($date));
            $days = date('t', strtotime($date));
            for ($i = 1; $i <= $days; $i++) {
                $today = $formatMonth . '-' . sprintf("%02d", $i);
                if (date('w', strtotime($today)) == 1) {
                    return $today;
                }
            }
        }
        return $date;
    }

    /*日报详情*/
    public function detail()
    {
        $id = $this->post('id');
        //数据查询
        $month = $this->post('month');//切换月份
        if ($month) {
            $date = $month . '-01';
            if ($this->post('type') == '周报') {
                $date = $this->findWeekOneDate($date);
            }
        } else {
            $date = $this->post('date') ?: $this->date;
            if ($this->post('type') == '周报') {
                while (1) {
                    if (date('w', strtotime($date)) != 1) {
                        $date = date('Y-m-d', strtotime("-1 day", strtotime($date)));
                    } else {
                        break;
                    }
                }
            } elseif ($this->post('type') == '月报') {
                $date = date('Y-m-01');
            }
        }
        $type = $this->post('type');
        $info = query(self::table, "id = '$id'");
        if (empty($type)) {
            $this->resp['warn'] = '未找到汇报类型';
        } elseif ($id && !$info['id']) {
            $this->resp['warn'] = '未找到此报告';
        } else {
            $date = $info['id'] ? $info['location'] : $date;
            if (in_array($type, ['日报', '周报'])) {
                if ($type == '日报') {
                    $dayResult = $this->dayReportCalendar($date);
                } else {
                    $dayResult = $this->weekReportCalendar($date);
                }
                if (!$info['id']) {
                    //审批人通过ID审批，其他人只能自己看自己
                    $info = query(self::table, "type = '$type' and location = '$date' and stid = '" . self::$stid . "'");
                }
                if ($info['id']) {
                    $fileArr = [];
                    $attachFile = find(array('table' => 'file', 'where' => "targetId = '$info[id]' order by time asc"));
                    foreach ($attachFile['array'] as $array) {
                        $fileArr[] = [
                            'id' => $array['id'],
                            'size' => self::formatSize($array['size']),
                            'format' => $array['format'],
                            'url' => self::fillSrc($array['src']),
                            'name' => $array['name']
                        ];
                    }
                    $staff = query('staff', "stid = '$info[stid]'");
                    $role = '';
                    if ($info['state'] == '草稿' && self::$stid == $info['stid']) {
                        $role = 'editor';
                    } elseif ($info['state'] == '待查看' && self::$stid == $info['auditor']) {
                        $role = 'auditor';
                    }
                    $record = self::auditRecord($info['id']);
                    $data['result'] = [
                        'pageType' => 'info',
                        'id' => $info['id'],
                        'location' => $info['location'],
                        'now' => $info['now'],
                        'next' => $info['next'],
                        'other' => $info['other'],
                        'state' => $info['state'],
                        'auditor' => $info['auditor'],
                        'auditorName' => self::findStaff($info['auditor']),
                        'staffName' => $staff['name'],
                        'ico' => self::fillSrc($staff['ico'], $staff['updateTime']),
                        'attachFile' => $fileArr,
                        'dayRecord' => $dayResult,
                        'type' => $type,
                        'now_date' => $date,
                        'now_month' => date('Y/m', strtotime($date)),
                        'next_month' => date('Y/m', strtotime($date)) == date('Y/m') ? '0' : '1',
                        'role' => $role,
                        'auditRecord'=>$record['record'],
                        'active'=>$record['active']
                    ];

                } else {
                    $data['result'] = [
                        'pageType' => 'edit',
                        'dayRecord' => $dayResult,
                        'type' => $type,
                        'now_date' => $date,
                        'now_month' => date('Y/m', strtotime($date)),
                        'next_month' => date('Y/m', strtotime($date)) == date('Y/m') ? '0' : '1',
                        'role' => '',
                        'auditRecord'=>[],
                    ];
                }
            } else {
                $dayResult = $this->monthReportCalendar($date);
                if (!$info['id']) {
                    $info = query(self::table, "type = '$type' and location = '$date' and stid = '" . self::$stid . "'");
                }
                if ($info['id']) {
                    $fileArr = [];
                    $attachFile = find(array('table' => 'file', 'where' => "targetId = '$info[id]' order by time asc"));
                    foreach ($attachFile['array'] as $array) {
                        $fileArr[] = [
                            'id' => $array['id'],
                            'size' => self::formatSize($array['size']),
                            'format' => $array['format'],
                            'url' => self::fillSrc($array['src']),
                            'name' => $array['name']
                        ];
                    }
                    $staff = query('staff', "stid = '$info[stid]'");
                    $role = '';
                    if ($info['state'] == '草稿' && self::$stid == $info['stid']) {
                        $role = 'editor';
                    } elseif ($info['state'] == '待查看' && self::$stid == $info['auditor']) {
                        $role = 'auditor';
                    }

                    $record = self::auditRecord($info['id']);
                    $data['result'] = [
                        'pageType' => 'info',
                        'id' => $info['id'],
                        'location' => $info['location'],
                        'now' => $info['now'],
                        'next' => $info['next'],
                        'other' => $info['other'],
                        'state' => $info['state'],
                        'auditor' => $info['auditor'],
                        'auditorName' => self::findStaff($info['auditor']),
                        'staffName' => $staff['name'],
                        'ico' => self::fillSrc($staff['ico'], $staff['updateTime']),
                        'attachFile' => $fileArr,
                        'dayRecord' => $dayResult,
                        'type' => $type,
                        'now_year' => date('Y', strtotime($date)),
                        'now_month' => date('Y-m', strtotime($date)),
                        'next_year' => date('Y', strtotime($date)) == date('Y') ? '0' : '1',
                        'role' => $role,
                        'auditRecord'=>$record['record'],
                        'active'=>$record['active']
                    ];

                } else {
                    $data['result'] = [
                        'pageType' => 'edit',
                        'dayRecord' => $dayResult,
                        'type' => $type,
                        'now_year' => date('Y', strtotime($date)),
                        'now_month' => date('Y-m', strtotime($date)),
                        'next_year' => date('Y', strtotime($date)) == date('Y') ? '0' : '1',
                        'role' => '',
                        'auditRecord'=>[],
                    ];
                }
            }
            //返回
            $this->code = 1;
            $this->resp['data'] = $data;
        }
    }

    /**
     * 审核记录
     * @param $id
     * @return array
     */
    public static function auditRecord($id): array
    {
        $active = 0;
        $record_list=[];
        $info = query(self::table,"id = '$id'");
        if ($info['state'] !='草稿'){
            $active = 0;
            // 类型
            $record_list[] = [
                'index' => 1,
                'text' => self::findStaff($info['stid'])."提交了汇报 ".$info['commitTime']
            ];
            if($info['state'] == '已查看'){
                $active = 2;
                $auditorTxt = self::findStaff($info['auditor']).'已阅 '.$info['passTime'];
                // 类型
                $record_list[] = [
                    'index' => 2,
                    'text' => $auditorTxt
                ];
            }elseif($info['state'] =='待查看'){
                $active = 1;
                // 类型
                $record_list[] = [
                    'index' => 2,
                    'text' => self::findStaff($info['auditor'])."待审阅"
                ];
            }
        }
        return ['active'=>$active,'record'=>$record_list];
    }


    /**
     * 编辑页面
     */
    public function editPage()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        $this->code = 1;
        $data = [];
        if ($id && empty($info['id'])) {
            $this->code = 0;
            $this->resp['warn'] = '未找到此' . self::title;
        } elseif (!empty($info['id'])) {
            $fileArr = [];
            $attachFile = find(array('table' => 'file', 'where' => "targetId = '$info[id]' order by time asc"));
            foreach ($attachFile['array'] as $array) {
                $fileArr[] = [
                    'id' => $array['id'],
                    'size' => self::formatSize($array['size']),
                    'format' => $array['format'],
                    'src' => self::fillSrc($array['src']),
                    'name' => $array['name']
                ];
            }
            $data['result'] = [
                'id' => $info['id'],
                'pageType' => 'edit',
                'location' => $info['location'],
                'now' => $info['now'],
                'next' => $info['next'],
                'other' => $info['other'],
                'type' => $info['type'],
                'attachFile' => $fileArr
            ];
        }
        $this->resp['data'] = $data;
    }

    /**
     * 编辑
     */
    public function commitEdit()
    {
        $id = $this->post('id') ?: self::getId();
        // 文件id
        $fileIdArr = (array)json_decode($_POST['fileId'], true);
        $field = [
            'location' => $this->post('location'),
            'now' => $this->post('now'),
            'next' => $this->post('next'),
            'other' => $this->post('other'),
            'type' => $this->post('type'),
        ];
        $annotation = [
            'location' => '当前日期',
            'now' => '今日工作',
            'next' => '明日计划',
            'other' => '其他事项',
            'type' => '报告类型',
        ];
        $rules = [
            'location' => 'required',
            'now' => 'required',
            'type' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (!empty($info['id']) && $info['state'] == '已查看') {
            $this->resp['warn'] = '当前日报已查看，不能编辑';
        } else {
            if (!$info['id']) {
                $orderNo = self::generateCode(self::page,[
                    'table' => self::table,
                    'prefix' => 'RE' . date('Ymd'),
                    'default' => '001'
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $orderNo,
                    'department' => self::findStaffDepartment(self::$stid),
                    'state' => '草稿',
                    'auditor' => $this->control['manager'],
                    'stid' => self::$stid,
                    'time' => $this->time
                ]);
                $this->resp['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $this->resp['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
                if (is_array($fileIdArr)) {
                    update([
                        'table' => 'file',
                        'field' => ['targetId' => $id],
                        'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"
                    ]);
                }
                //添加日志
                $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $this->code = 1;
                $this->resp['data']['id'] = $id;
            }
        }
        resp:
    }

    /**
     * 统计
     */
    public function statistics()
    {
        $yesterday = date('Y-m-d', strtotime("-1 day"));
        //统计昨天的直属下级日报
        $total = self::total(array('table' => 'staff', 'where' => "manager = '" . self::$stid . "' and state !='离职'"));
        $reportNum = self::total(array('table' => self::table, 'where' => "stid in (select stid from staff where manager = '" . self::$stid . "' and state !='离职') and type = '日报' and location = '$yesterday'"));
        $data['dayReport'] = [
            'title' => '昨日',
            'ico' => oaIndexAppClass::icon('dayReport'),
            'total' => $total,
            'reportNum' => $reportNum,
            'unReportNum' => $total - $reportNum
        ];
        //统计直属下级本周周报
        $nowWeek = date('Y-m-d', strtotime('last sunday +1 day'));
        $reportNum = self::total(array('table' => self::table, 'where' => "stid in (select stid from staff where manager = '" . self::$stid . "' and state !='离职') and type = '周报' and location = '$nowWeek'"));
        $data['weekReport'] = [
            'title' => '本周',
            'ico' => oaIndexAppClass::icon('weekReport'),
            'total' => $total,
            'reportNum' => $reportNum,
            'unReportNum' => $total - $reportNum
        ];

        //统计直属下级本月月报
        $monthDate = date('Y-m-01');
        $reportNum = self::total(array('table' => self::table, 'where' => "stid in (select stid from staff where manager = '" . self::$stid . "' and state !='离职') and type = '月报' and location = '$monthDate'"));
        $data['monthReport'] = [
            'title' => '本月',
            'ico' => oaIndexAppClass::icon('monthReport'),
            'total' => $total,
            'reportNum' => $reportNum,
            'unReportNum' => $total - $reportNum
        ];
        $this->code = 1;
        $this->resp['data']['result'] = $data;
    }


    /**
     * 列表
     */
    public function list()
    {
        if ($this->post('role') == 'auditor') {
            $and = " and auditor = '" . self::$stid . "' and state = '待查看'";
        } else {
            $and = " and stid = '" . self::$stid . "'";
        }
        //全等查询数组
        $equal = array(
            "type" => $this->post('type'),//报告类型
        );

        $commitTime = $this->post('commit_time');
        if (!$commitTime) {
            if ($this->post('startDate')) {
                $commitTime = $this->post('startDate');
            }
            if ($this->post('endDate')) {
                $commitTime .= empty($commitTime) ? $this->post('endDate') : ('~' . $this->post('endDate'));
            }
        }
        if ($commitTime) {
            $and.= self::miniTimeComparison($commitTime,field: 'commitTime');
        }
        //获取查询结果
        $where = search(array("=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));
        //数据分析
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $staff = query("staff", "stid = '$array[stid]'");
            $data['result'][] = array(
                "id" => $array['id'],//ID
                'type' => $array['type'],
                "staffName" => $staff['name'],//申请人
                "now" => zishu($array['now'], 15, false),
                'next' => zishu($array['next'], 15, false) ?: ' ',
                "title" => $staff['name'] . '的' . $array['type'],
                "state" => $array['state'],
                'time' => date('m/d', strtotime($array['time']))
            );
        }
        $data['page'] = $page['para'];

        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }

    /**
     * 提交审阅
     */
    public function commitAudit()
    {
        $id = $this->post('id');
        $page = $this->post('page') ?: 'workReportDay';
        $act = 'edit';
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        if (!$this->power($page, $act)) {
            $this->resp['warn'] = "你没有此权限的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此报告";
        } elseif ($info['state'] != '草稿') {
            $this->resp['warn'] = '此报告不是草稿状态，不能提交';
        } elseif (empty($this->control['manager'])) {
            $this->resp['warn'] = '您还没有上级来审阅此报告';
        } else {
            $fieldVlaue = ($info['state'] == '草稿') ? '待查看' : '草稿';
            // 修改状态
            $this->resp['warn'] = static::update([
                "table" => self::table,
                'field' => [
                    'auditor' => $this->control['manager'],
                    'state' => $fieldVlaue,
                    'commitTime' => $this->time
                ],
                "where" => $where
            ]);
            if ($this->resp['warn'] == '更新成功') {
                $this->code = 1;
                $this->resp['warn'] = '提交成功';
                //添加记录
                $text = "{$this->control['name']}提交了一条" . self::title . "：ID【{$id}】" . (isset($info['title']) ? "，标题【{$info['title']}】" : '') . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
            } else {
                $this->resp['warn'] = '提交失败';
            }
        }
        resp:
    }

    /**
     * 获取审批意见
     */
    public function getAuditPage()
    {
        $id = $this->post('id');
        $page = $this->post('page') ?: 'weekReportDay';
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        if (!$this->power($page, 'see')) {
            $this->resp['warn'] = "你没有审阅的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此报告";
        } elseif ($info['state'] != '待查看') {
            $this->resp['warn'] = '此报告不是待查看状态，不能审阅';
        } elseif (empty($info['auditor'])) {
            $this->resp['warn'] = '未找到此报告的审阅人';
        } elseif ($info['auditor'] != self::$stid) {
            $this->resp['warn'] = '您不是此报告的审阅人';
        } else {
            $this->code = 1;
            $this->resp['data'] = [
                'level' => ['优', '良', '中', '差']
            ];
        }
    }

    /**
     * 审阅
     */
    public function review()
    {
        $id = $this->post('id');
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        if (!$this->power(self::page, 'see')) {
            $this->resp['warn'] = "你没有审阅的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此报告";
        } elseif ($info['state'] != '待查看') {
            $this->resp['warn'] = "此报告不是待查看状态";
        } elseif ($info['auditor'] != self::$stid) {
            $this->resp['warn'] = "审阅失败，非直属上级";
        } else {
            $text = '';
            // 修改field
            $fieldKey = 'state';
            $fieldVlaue = ($this->post('state') == '通过') ? '已查看' : '草稿';
            // 修改状态
            $warn = static::update([
                "table" => self::table,
                'field' => [
                    $fieldKey => $fieldVlaue,
                    'rate' => $this->post('level'),
                    'text' => $this->post('text'),
                    'passTime' => $this->time,
                ],
                "where" => $where
            ]);
            if ($warn == '更新成功') {
                //添加记录
                $text .= "{$this->control['name']}审阅了一条" . self::title . "：ID【{$id}】" . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
                $this->resp['warn'] = '审阅成功';
            } else {
                $this->resp['warn'] = '审阅失败';
            }
        }
        resp:
    }

    /**
     * 删除
     */
    public function delete()
    {
        $id = $this->post('id');
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'del')) {
            $this->resp['warn'] = "你没有删除的权限";
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = "未找到此报告";
        } elseif ($info['stid'] != self::$stid) {
            $this->resp['warn'] = "这不是你的报告";
        } elseif ($info['state'] != '草稿') {
            $this->resp['warn'] = "此报告不是草稿状态，不能删除";
        } else {
            $warn = delete(array('table' => self::table, 'where' => "id = '$id'"));
            if ($warn == '删除成功') {
                //添加记录
                $text = "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . '<br>';
                // 写入日志
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
                $this->resp['warn'] = '删除成功';
            } else {
                $this->resp['warn'] = '删除失败';
            }
        }
        resp:
    }

}
